package org.example.classtopia.Service.Impl;

import org.example.classtopia.Model.dto.CategoryCreateDTO;
import org.example.classtopia.Model.dto.CategoryUpdateDTO;
import org.example.classtopia.Model.Entity.Category;
import org.example.classtopia.Model.vo.CategoryVO;
import org.example.classtopia.Service.CategoryService;
import org.example.classtopia.Mapper.CategoryMapper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 分类服务实现
 */
@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public Category createCategory(CategoryCreateDTO categoryCreateDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryCreateDTO, category);
        LocalDateTime now = LocalDateTime.now();
        category.setCreatedAt(now);
        category.setUpdatedAt(now);
        int rows = categoryMapper.insertCategory(category);
        return rows > 0 ? category : null;
    }

    @Override
    public CategoryVO getCategoryById(Long id) {
        Category category = categoryMapper.selectCategoryById(id);
        if (category == null) {
            return null;
        }
        CategoryVO vo = new CategoryVO();
        BeanUtils.copyProperties(category, vo);
        return vo;
    }

    @Override
    public List<CategoryVO> getAllCategories(int offset, int limit) {
        List<Category> categories = categoryMapper.selectAllCategories(offset, limit);
        return categories.stream().map(category -> {
            CategoryVO vo = new CategoryVO();
            BeanUtils.copyProperties(category, vo);
            return vo;
        }).collect(Collectors.toList());
    }

    @Override
    public boolean updateCategory(CategoryUpdateDTO categoryUpdateDTO) {
        Category category = new Category();
        BeanUtils.copyProperties(categoryUpdateDTO, category);
        category.setUpdatedAt(LocalDateTime.now());
        int rows = categoryMapper.updateCategory(category);
        return rows > 0;
    }

    @Override
    public boolean deleteCategoryById(Long id) {
        int rows = categoryMapper.deleteCategoryById(id);
        return rows > 0;
    }

    @Override
    public List<CategoryVO> getCategoriesByStatus(Byte status, int offset, int limit) {
        List<Category> categories = categoryMapper.selectCategoriesByStatus(status, offset, limit);
        return categories.stream().map(category -> {
            CategoryVO vo = new CategoryVO();
            BeanUtils.copyProperties(category, vo);
            return vo;
        }).collect(Collectors.toList());
    }
}
